package net.quanter.shield.dubbo.filter;

import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import net.quanter.shield.common.dto.context.InvocationContextDTO;
import net.quanter.shield.common.dto.context.InvocationDTO;
import net.quanter.shield.utils.invocation.InvocationUtil;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;

/***
 *
 * created on 2020-10-09
 * @author 王老实
 *
 */
@Activate(group = CommonConstants.PROVIDER)
public class DubboDebugProviderFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        InvocationContextDTO contextDTO = (InvocationContextDTO)invocation.getObjectAttachment("DubboContextDTO");
        if (contextDTO != null) {
            InvocationUtil.begin(contextDTO);
        }
        try {
            Result result = invoker.invoke(invocation);
            if (contextDTO != null) {
                List<InvocationDTO> chain = InvocationUtil.getInvocationChain();
                if (CollectionUtil.isNotEmpty(chain)) {
                    result.setObjectAttachment("dubboChain", chain);
                }
            }
            return result;
        } finally {
            if (contextDTO != null) {
                InvocationUtil.end();
            }
        }

    }
}
